<?php
namespace app\app\controller\v1;
use app\app\Appbase;
use think\facade\Session;
use think\facade\Cache;
use auth\Api;
use think\Image;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Response\QrCodeResponse;

//
//用户
//
class user extends Appbase 
{
	
	/**
	* 获取用户信息
	* /app/v1/user/getUserInfo
	* 是否需要登录 
	* @is_need_login true
	*/
	public function getUserInfo(){
		$request =  request();
		$uid = $request ->userId;
		try {
			//TODO 用户信息
	        $userInfo = $request ->userInfo;
	        // TODO 订单信息
	        $order = model('order');
			$where[] = ['uid','=',$uid];
			$where[] = ['is_del','=',0];
	        $order_sum = [
	        	"dfk"=> $order->where($where)->where('status', 0)->where('is_pay', 0)->count(),
	        	"dfh"=> $order->where($where)->where('status', 0)->where('is_pay', 1)->count(),
	        	"yfh"=> $order->where($where)->where('status', 1)->count(),
	        	"ysh"=>$order->where($where)->where('status', 2)->count(),
	        	"dpj"=> $order->where($where)->where('status', 3)->count(),
	        ];
			// TODO 其他other
	        $other = [
	        	"collect_num"=> model('userStars')->where('uid',$uid)->where('type','collect')->count(),
	        	"coupon_num"=> count(model('CouponUser')->getUserCouponList($uid)),
	        ];
			//返回
			return $this->ReSucess( compact('userInfo','order_sum','other') );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 获取用户收藏列表
	* /app/v1/user/myCollect
	* 是否需要登录 
	* @is_need_login true
	*/
	public function myCollect($type=0){
		try {
			$result = model('UserStars')->userCollectList(request()->userId,$type);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 用户申请代理
	* /app/v1/user/applyAgent
	* 是否需要登录 
	* @is_need_login true
	*/
	public function applyAgent(){
		$request =  request();
		$param = $request ->post();
		$param['uid'] = $request ->userId;
		if($request->userInfo['is_partner'] == 1){
			return $this->ReError('您已是代理商，无须重复申请！');
		}
		if(model('UserApplyAgent')->where('uid',$param['uid'] )->where('is_del',0)->where('status',0)->find() ){
			return $this->ReError('您已申请，等待后台审核！');
		}
		try {
			$result = model('UserApplyAgent')->add($param);
			if($result === false){
				return $this->ReError( model('UserApplyAgent')->errorInfo );
			}
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 我的推广
	* /app/v1/user/mySpread
	* 是否需要登录 
	* @is_need_login true
	*/
	public function mySpread(){
		$uid = request()->userId;
		try {
			
			//累计佣金
			$data['total_brokerage'] = model('user_bill')->alias('a')
				->leftJoin('user b','a.uid = b.id')
				->where('a.uid',$uid)
//				->where('a.shop_id = b.shop_id')
				->where('a.status',1)
				->where('a.category','brokerage')
				->where('a.pm',1)
				->sum('number');
			
			//总推广人数
			$data['total_spread']	 =  model('User')->where("spread_uid",$uid)->count();
			
			//累计提现
			$data['total_withdraw']	 =  model('user_extract')->alias('a')
				->leftJoin('user b','a.uid = b.id')
				->where('a.uid',$uid)
				->where('a.shop_id = b.shop_id')
				->where('a.status',1)
				->where('a.money_type','brokerage')
				->sum('extract_price');

			return $this->ReSucess( $data );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 我的推广列表
	* /app/v1/user/mySpreadList
	* 是否需要登录 
	* @is_need_login true
	*/
	public function mySpreadList(){
		try {
			$data = model('User')->getShareList( request()->userId );
			return $this->ReSucess( $data );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 待维护人脉
	* /app/v1/user/dwhrm
	* 是否需要登录 
	* @is_need_login true
	*/
	public function dwhrm(){
		$uid = request()->userId;
		$shopId =  request()->shopId;

		try {
	        $table  = model('ShopYyOrder')->order('id desc')->where('status',1)->limit(10000000)->buildSql();
			$model = model('user')->alias('u')
				->leftJoin('user_vip a','u.id = a.uid')
	        	->leftJoin("$table c",'c.uid = u.id and c.shop_id=u.shop_id')
	        	->leftJoin('user_yg_proj y','y.id = c.proj_id')
	        	->leftJoin('goods b','b.id = y.goods_id')
				->leftJoin('goods_specs d','d.id = y.specs_id')
				->field("u.id as uid,ifnull(a.name,u.nickname) as user_name,a.phone,a.birthday")
				->field("u.avatarurl")
	    		->field("c.proj_id as proj_id")
	    		->field("concat(b.name,' / ',d.name) as proj_name")
	    		->field("datediff(ifnull(c.add_time,u.add_time) ,now()) as day")
	    		->group('u.id');
        	
        	$model = $model->whereExp("-30",">= ifnull(datediff(c.add_time,now()),datediff(u.add_time,now()))");
        	$model = $model->where('u.shop_id',$shopId);	
        	$model = $model->where('u.spread_uid',$uid);	
	    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
   
        	$data =[];
        	foreach( $model->select() as $key => $value ){
    			$value['count']  = model('ShopYyOrder')->where('status',1)->where('uid',$value['uid'])->count();
    			$value['consume'] = model('user')->consume($value['uid'],$shopId);	
    			$data[] = $value;
        	}	
        	
			//返回
			return $this->ReSucess($data);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 生成我的二维码
	* /app/v1/user/myQrCode
	* 是否需要登录 
	* @is_need_login false
	*/
	public function myQrCode($size = 120){
		$uid = request() ->userId;
		try {
			//文件地址
			$path = 'images/bill/poster/uid_'.$uid.'_qrcode.png';
			
			//二维码地址
			$url = APP_PATH.'/wx/inlet?scene='.$uid;
			
			//生成二维码
			$qrCode = new QrCode($url);
	        $qrCode->setSize( $size ?: 120 );
	        $qrCode->setWriterByName('png');
	        $qrCode->setMargin(10);
	        $qrCode->setEncoding('UTF-8');
	        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
	        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
	        $qrCode->setLogoSize(150, 200);
	        $qrCode->setRoundBlockSize(true);
	        $qrCode->setValidateResult(false);
	        $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);
	        $qrCode->writeFile($path);
	        
	      	return $this->ReSucess(APP_PATH.'/'.$path.'?time='.time());	
	      	
	        //header('Content-Type: '.$qrCode->getContentType());
	        //echo $qrCode->writeString(); die;
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 我的佣金明细
	* /app/v1/user/myBrokerageBill
	* 是否需要登录 
	* @is_need_login true
	*/
	public function myBrokerageBill(){
		$request =  request();
		$userInfo = $request ->userInfo;
		$uid = $request ->userId;
		try {
			$total_brokerage = $userInfo['brokerage'];
			$list = model('UserBill')->userBillList($uid,'brokerage');
			return $this->ReSucess(compact( 'list', 'total_brokerage'));	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 我的积分明细
	* /app/v1/user/myIntegralBill
	* 是否需要登录 
	* @is_need_login true
	*/
	public function myIntegralBill(){
		$request =  request();
		$userInfo = $request ->userInfo;
		$uid = $request ->userId;
		try {
			$total_integral = $userInfo['integral'];
			$list = model('UserBill')->userBillList($uid,'integral');
			return $this->ReSucess(compact( 'list', 'total_integral'));	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 我的余额明细
	* /app/v1/user/myBalanceGiveBill
	* 是否需要登录 
	* @is_need_login true
	*/
	public function myBalanceGiveBill(){
		$request =  request();
		$userInfo = $request ->userInfo;
		$uid = $request ->userId;
		try {
			$total_balance = $userInfo['balance_gift'];
			$list = model('UserBill')->userBillList($uid,'balance_gift');
			return $this->ReSucess(compact( 'list', 'total_balance'));	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 消费记录
	* /app/v1/user/myConsumeBill
	* 是否需要登录 
	* @is_need_login true
	*/
	public function myConsumeBill($type='*'){
		$request =  request();
		$userInfo = $request ->userInfo;
		$uid = $request ->userId;
		try {
			$list = model('UserBill')->userBillList($uid,$type);
			return $this->ReSucess($list);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 用户申请提现
	* /app/v1/user/withdraw
	* 是否需要登录 
	* @is_need_login true
	* @method post 
	*/
	public function withdraw(){
		try {
			$request =  request();
         	$result = model('UserExtract')->userExtract($request ->userId,$request->post());
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 获取用户提现记录
	* /app/v1/user/withdrawLog
	* 是否需要登录 
	* @is_need_login true
	* @method post 
	*/
	public function withdrawLog(){
		$uid = request() ->userId;
		try {
			//TODO 提现列表
	        $extractList = model('UserExtract')->extractList($uid);
			//TODO 累积已提现
	        $extractSum =  model('UserExtract')->extractSum($uid);
			//TODO 获得用户提现总金额-不论成败
	        $extractTotal =  model('UserExtract')->userExtractTotalPrice($uid);
			//----
			return $this->ReSucess(compact('extractList','extractSum','extractTotal') );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 获取我的授权书
	* /app/v1/user/myAuthorize
	* 是否需要登录 
	* @is_need_login true
	* @method all 
	*/
	public function myAuthorize(){
		$vipInfo = request() ->userInfo->vip_info;
		try {
			$src = '';
			if($vipInfo){
				$bg = model('UserLevel')->where('level',$vipInfo['level'])->value('certificate_template');
				//临时文件地址
				$path = public_path().'/images/bill/poster/';
				$savePath = 'images/bill/poster/certificate.png';
				$ttf = public_path().'/simsun.ttf';
				//背景
				copy($bg,$path.'certificate-bg.jpg');
				$image = Image::open($path.'certificate-bg.jpg');
				//添加文本			
				$times = date( 'Y-m-d', strtotime($vipInfo['upgrade_time'] ?: $vipInfo['add_time'] )) ;
				$image->text($vipInfo['name'],$ttf,11,'#000',[94,290])
					->text($vipInfo['level_name'],$ttf,11,'#000',[290,290])
					->text($times,$ttf,10,'#000',[260,561])
					->save($savePath);
				//获得路径
				$src = APP_PATH.$savePath .'?t='.time();
			}
			
			return $this->ReSucess(compact('src') );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 门店变更
	* /app/v1/user/changeShop
	* 是否需要登录 
	* @is_need_login true
	* @is_vip true
	*/
	public function changeShop($shop_id){
		try {
			$uid = request() ->userId;
			$this_shop_id = request() ->userInfo['shop_id'];
			$status = model("UserChangeShop")->addApply($uid,$this_shop_id,$shop_id);
			return $this->ReSucess($status,'申请成功，请等待审核！');	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 签到
	* /app/v1/user/signiIn
	* 是否需要登录 
	* @is_need_login true
	*/
	public function signIn(){
		try {
			$uid = request() ->userId;
			$shop_id = request() ->userInfo['shop_id'];
			$res =  model('UserSignLog')->signIn($uid,$shop_id);
			return $this->ReSucess('签到成功获取'.$res.'积分');	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
}



